#include <stdio.h>
#include <sqlite3.h>
#include <time.h>
int sqlite_func();
int main()
{
	time_t timep;
	time(&timep);
	struct tm *p=gmtime(&timep);
	char str1[]={"temp"},str2[]={"humi"};
	printf("Content-type: text/html\n\n");
	printf("<html>\n");
	printf("<head>\n");
	//printf("<meta http-equiv=\"Refresh\" content=\"1\">");
//	fprintf(cgiOut,"<meta http-equiv=\"Refresh\" content=\"3;URL=/indexURL=/index.html.html\">");	
	printf("<script>");
	printf("setTimeout(function(){location.reload()},2000);\n");
	printf("</script>");
	printf("<title>CGI Output</title>\n");
	printf("</head>\n");
	//while(1){
		printf("<body>");
		printf("<h1><center>智慧农场环境监测系统</center> </h1>");
		printf("<center><table boder=\"5\",align=\"center\" bgcolor=\"#0ebfaa\">");
		printf("<tr>");
		printf("<td><font size=\"5\">温  度：</font></td>\n");
		printf("<td align=\"center\">\n");
		printf("<font size=\"5\">\n");
		sqlite_func();
		printf("</font>");
		printf("</td>\n");
		printf("</tr\n>");
		printf("<tr>");
		printf("<td><font size=\"5\">湿  度：</font></td>\n");
		printf("<td align=\"center\"><font size=\"5\">\n");
		sqlite_func();
		printf("</td></font>\n");
		printf("</tr\n>");
		printf("<tr>\n");
		printf("<td><font size=\"5\">时  间：</font></td>\n");
		printf("<td><font size=\"5\">\n");
		printf("%d/%d/%d", (1900+p->tm_year), (1+p->tm_mon), p->tm_mday); 
		 printf(" %d:%d:%d\n", (8+p->tm_hour), p->tm_min, p->tm_sec);
		printf("</td></font>\n");
		printf("</tr>\n");
		printf("<tr align=\"center\"><td><button type=\"button\" onclick=\'location.href=(\"http://47.98.123.181/cgi-bin/w_m1.cgi\")\'>开灯 </button></td>");
		printf("<td><button type=\"button\"> 关灯</button></td></tr>\n");
		printf("</table></center>\n");
		//printf("<button type=\"button\"> shghg </button>");
		printf("</body>");
		printf("</html>\n");
		return 0;
	//}
}
int sqlite_func()
{
	sqlite3 *db;
	int nrow = 0, ncolumn = 0;
	char **azResult = NULL;
	char *zErrMsg = 0; 
	char sql[500];
	int rc = 0;
	
	rc = sqlite3_open("/xuedao", &db);
	if (rc)
	{
		printf("Content-type: text/html\n\n");
		fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
		sqlite3_close(db);
		//return sql_errror();
	}
	sprintf(sql, "insert into w_2(id,t2,t3) values(1,2,4);");	
 
	rc = sqlite3_get_table( db , sql , &azResult , &nrow , &ncolumn , &zErrMsg );
	if (rc != SQLITE_OK)
	{
		printf("Content-type: text/html\n\n");
		fprintf(stderr, "SQL error: %s\n", zErrMsg);
		sqlite3_close(db);
	//	return sql_errror();
	}

	if(*azResult != NULL)
	{
		//printf("Content-type: text/html\n\n");
		int i;
		//for( i=0 ; i<( nrow + 1 ) * ncolumn ; i++ )
			printf( "%s\n",  *(azResult+1) );
	}
}
